package com.zzyl.nursing.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.ThreadLocalUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.service.IReservationService;

/**
 * 预约Service业务层处理
 * 
 * @author zzyl
 */
@Service
public class ReservationServiceImpl implements IReservationService 
{
    private static final Logger log = LoggerFactory.getLogger(ReservationServiceImpl.class);
    
    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 查询预约
     * 
     * @param id 预约主键
     * @return 预约
     */
    @Override
    public Reservation selectReservationById(Long id)
    {
        return reservationMapper.selectReservationById(id);
    }

    /**
     * 查询预约列表
     * 
     * @param reservation 预约
     * @return 预约
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation)
    {
        return reservationMapper.selectReservationList(reservation);
    }

    /**
     * 新增预约
     * 
     * @param reservation 预约
     * @return 结果
     */
    @Override
    public int insertReservation(Reservation reservation)
    {
        try {
            log.info("开始插入预约，原始数据：{}", reservation);
            reservation.setCreateTime(new Date());
            Long userId = ThreadLocalUtil.get();
            if (userId == null) {
                log.error("用户ID为空，无法创建预约");
                throw new RuntimeException("用户未登录");
            }
            reservation.setCreateBy(String.valueOf(userId));
            log.info("设置用户ID：{}", ThreadLocalUtil.get());
            log.info("最终预约数据：{}", reservation);
            int result = reservationMapper.insertReservation(reservation);
            log.info("插入预约结果：{}", result);
            if (result <= 0) {
                log.error("插入预约失败，影响行数：{}", result);
            }
            return result;
        } catch (Exception e) {
            log.error("插入预约异常", e);
            throw e;
        }
    }

    /**
     * 修改预约
     * 
     * @param reservation 预约
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation)
    {
        reservation.setUpdateTime(new Date());
        Long userId = ThreadLocalUtil.get();
        if (userId == null) {
            log.error("用户ID为空，无法更新预约");
            throw new RuntimeException("用户未登录");
        }
        reservation.setUpdateBy(String.valueOf(userId));
        return reservationMapper.updateReservation(reservation);
    }

    /**
     * 批量删除预约
     * 
     * @param ids 需要删除的预约主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids)
    {
        return reservationMapper.deleteReservationByIds(ids);
    }

    /**
     * 删除预约信息
     * 
     * @param id 预约主键
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id)
    {
        return reservationMapper.deleteReservationById(id);
    }

    /**
     * 查询当天取消预约数量
     * 
     * @return 取消预约数量
     */
    @Override
    public int selectCancelledCount()
    {
        Long userId = ThreadLocalUtil.get();
        if (userId == null) {
            log.error("用户ID为空，无法查询取消预约次数");
            return 0;
        }
        return reservationMapper.selectCancelledCountByUserId(String.valueOf(userId));
    }



    /**
     * 查询每个时间段剩余预约次数
     * 
     * @param time 时间戳
     * @return 时间段剩余预约次数列表
     */
    @Override
    public List<Map<String, Object>> selectCountByTime(Long time)
    {
        // 根据时间戳获取当天开始和结束时间
        Date date = new Date(time);
        Date startTime = Date.from(LocalDateTimeUtil.of(date).toLocalDate().atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toInstant());
        Date endTime = Date.from(LocalDateTimeUtil.of(startTime).plusDays(1).atZone(java.time.ZoneId.systemDefault()).toInstant());
        
        return reservationMapper.selectCountByTime(startTime, endTime);
    }

    /**
     * 取消预约
     * 
     * @param id 预约ID
     * @return 结果
     */
    @Override
    public int cancelReservation(Long id)
    {
        Long userId = ThreadLocalUtil.get();
        if (userId == null) {
            log.error("用户ID为空，无法取消预约");
            throw new RuntimeException("用户未登录");
        }
        
        // 检查当天取消次数是否超过3次
        int cancelledCount = reservationMapper.selectCancelledCountByUserId(String.valueOf(userId));
        if (cancelledCount >= 3) {
            log.error("用户{}当天取消次数已达{}次，无法再次取消", userId, cancelledCount);
            throw new RuntimeException("当天取消次数已达上限，无法再次取消");
        }
        
        // 检查预约状态是否为待上门
        Reservation existingReservation = reservationMapper.selectReservationById(id);
        if (existingReservation == null) {
            throw new RuntimeException("预约不存在");
        }
        if (existingReservation.getStatus() != 0) {
            throw new RuntimeException("只有待上门状态的预约才能取消");
        }
        
        Reservation reservation = new Reservation();
        reservation.setId(id);
        reservation.setStatus(2); // 已取消
        reservation.setUpdateTime(new Date());
        reservation.setUpdateBy(String.valueOf(userId));
        return reservationMapper.updateReservation(reservation);
    }



    /**
     * 完成预约（后台核销）
     * 
     * @param id 预约ID
     * @return 结果
     */
    @Override
    public int completeReservation(Long id)
    {
        // 检查预约状态是否为待上门
        Reservation existingReservation = reservationMapper.selectReservationById(id);
        if (existingReservation == null) {
            throw new RuntimeException("预约不存在");
        }
        if (existingReservation.getStatus() != 0) {
            throw new RuntimeException("只有待上门状态的预约才能完成");
        }
        
        Reservation reservation = new Reservation();
        reservation.setId(id);
        reservation.setStatus(1); // 已完成
        reservation.setUpdateTime(new Date());
        reservation.setUpdateBy("admin"); // 后台操作
        return reservationMapper.updateReservation(reservation);
    }

    /**
     * 更新过期预约状态
     * 
     * @return 更新的记录数
     */
    @Override
    public int updateExpiredReservations()
    {
        return reservationMapper.updateExpiredReservations();
    }
} 